﻿CREATE FUNCTION [QIC].[CallFactory_VINSERT](@Token QIC.TokenTable READONLY, @CallerId INT, @CalleeId INT, @ReturnPropertName VARCHAR(50), @TokenMap VARCHAR(50), @Indent INT, @CalleeDelegateName varchar(50))
RETURNS VARCHAR(MAX)
AS
BEGIN
 
	DECLARE @Call VARCHAR(MAX) 
	DECLARE @SelectValues VARCHAR(MAX)
	DECLARE @InsertColumns VARCHAR(MAX)
	DECLARE @CalleeView VARCHAR(MAX)
	DECLARE @LocalToken QIC.TokenTable
	DECLARE @TargetToken QIC.TokenTable
 
	SELECT @CalleeView = QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(name) from sys.objects WHERE object_id = @CalleeId
 
	INSERT INTO @TargetToken (IsOutPut,IsReadOnly,MaxLength,ObjectId,Precision,PropertyId,PropertyName,Scale,UserTypeId)
	SELECT 0,0,0,token.ObjectId,0,token.PropertyId,token.PropertyName,0,0 FROM @Token token
	INNER JOIN sys.columns Targetcolumns
		ON Targetcolumns.object_id = token.ObjectId
		AND Targetcolumns.column_id = token.PropertyId
		AND Targetcolumns.is_computed = 0
		AND Targetcolumns.is_identity = 0
	WHERE token.ObjectId = @CalleeId
 
	SET @InsertColumns = ''
	SELECT @InsertColumns += QUOTENAME(Targetcolumns.PropertyName) + ', '
	FROM @TargetToken Targetcolumns
	ORDER BY Targetcolumns.PropertyId
 
	IF @InsertColumns = '' RETURN ''
	SET @InsertColumns = LEFT(@InsertColumns,DATALENGTH(@InsertColumns) - 2)
 
	INSERT INTO @LocalToken (IsOutPut,IsReadOnly,MaxLength,ObjectId,Precision,PropertyId,PropertyName,Scale,UserTypeId)
	SELECT 0,0,0,ObjectId,0,PropertyId,PropertyName,0,0 FROM @Token 
	WHERE ObjectId = @CallerId OR (PropertyName LIKE '@%') OR (PropertyName LIKE '''%''')
 
	SET @SelectValues = ''
	SELECT @SelectValues += QIC.TokenSubstitute(@LocalToken, targetToken.PropertyName, @TokenMap)	+ ', '
	FROM @TargetToken targetToken
	LEFT OUTER JOIN @Token sourceToken
		ON sourceToken.ObjectId = @CallerId
		AND QIC.TokenSubstitute(@LocalToken, sourceToken.PropertyName, @TokenMap) =  targetToken.PropertyName
	WHERE targetToken.ObjectId = @CalleeId
	ORDER BY targetToken.PropertyId
 
	IF @SelectValues <> '' SET @SelectValues = LEFT(@SelectValues,DATALENGTH(@SelectValues) - 2)
	SET @SelectValues = ISNULL(@SelectValues,'')
 
	SET @Call = ''
	SET @Call += 
		QIC.Indent(@Indent) + 'INSERT INTO ' + @CalleeView + ' (' + @InsertColumns + ') ' + QIC.LB() +
		QIC.Indent(@Indent) + 'SELECT ' + @SelectValues + ' FROM inserted'
 
	RETURN @Call
 
END